'use strict'
const EventEmitter = require('events')
const Client = require('../client')
const Packet = require('./packet')
const RoomHttp = require('../roomhttp')
var host = 'openbarrage.douyutv.com'
var port = 8601
const api = 'http://open.douyucdn.cn/api/RoomApi/room/'
class DyRoom extends EventEmitter {
  constructor (roomId) {
    super()
    this.count = 0
    this.roomId = ''
    this.isInit = false
    this.isLive = true // 是否在直播
    this.info = null
    this.client = new Client(port, host, 45 * 1000, this.keepAlive.bind(this))
    this.client.on('onConnect', this.onConnect.bind(this))
    this.client.on('onData', this.onData.bind(this))
    this.roomHttp = new RoomHttp()
    this.roomHttp.on('info', this.onInfo.bind(this))
    this.roomHttp.get(api.concat(roomId))
  }
  onInfo (obj) {
    if (obj && obj.error === 0) {
      if (!this.isInit) {
        this.emit('init', obj)
        this.roomId = obj.data.room_id
        this.client.start()
        this.isInit = true
      } else {
        this.emit('update', obj)
      }
      this.info = obj
    } else {
      if (!this.isInit) {
        this.emit('init', null)
      }
    }
  }
  keepAlive () {
    this._send({
      type: 'keepalive',
      tick: Math.floor(new Date()
        .getTime() * 0.001)
    })
    if (this.isLive) {
      this.roomHttp.get(api.concat(this.roomId))
    }
  }
  destroy () {
    this.client.close()
  }
  onConnect () {
    this._send({
      type: 'loginreq',
      roomid: this.roomId
    })
  }
  onData (strHex) {
    var msg = Packet.toJson(strHex)
    if (!msg) {
      return
    }
    let type = msg.type
    try {
      if (type === 'loginres') {
        this._send({
          type: 'joingroup',
          rid: this.roomId,
          gid: '-9999'
        })
      } else if (type === 'chatmsg' || type === 'dgb' || type === 'uenter') {
        var date = new Date()
        msg.serverdate = date.getHours() + ':' + date.getMinutes()
        this.emit('data', msg)
      } else if (type === 'rss') {
        this.emit('data', msg)
        if (msg.ss === '0') { // 没有直播
          this.isLive = false
        } else { // 正在直播
          this.isLive = true
        }
      }
    } catch (e) {

    } finally {

    }
  }
  _send (obj) {
    this.client.send(Packet.toBuffer(obj))
  }
}
module.exports = DyRoom
